package app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import app.BaseAppV1;
import beans.TrafficPageViewBean;
import common.Constant;
import utils.AtguiguUtil;
import utils.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * @Author lzc
 * @Date 2022/10/17 08:58
 */
public class Dws_02_DwsTrafficVcChArIsNewPageViewWindow extends BaseAppV1 {
    public static void main(String[] args) {
        new Dws_02_DwsTrafficVcChArIsNewPageViewWindow().init(4002, 2, "Dws_02_DwsTrafficVcChArIsNewPageViewWindow", Constant.TOPIC_DWD_TRAFFIC_PAGE);
    }

    @Override
    protected void handle(StreamExecutionEnvironment env, DataStreamSource<String> stream) {
        // 1. 封装到一个 pojo 中
        SingleOutputStreamOperator<TrafficPageViewBean> beanStream = parseToPojo(stream);
        // 2. 开窗聚和
        SingleOutputStreamOperator<TrafficPageViewBean> resultStream = windowAndAgg(beanStream);
        // 3. 写出到 clickhouse 中
        writeToClickhouse(resultStream);
    }

    private void writeToClickhouse(SingleOutputStreamOperator<TrafficPageViewBean> resultStream) {
        resultStream.addSink(FlinkSinkUtil.getClickHouseSink("dws_traffic_vc_ch_ar_is_new_page_view_window", TrafficPageViewBean.class));
    }

    private SingleOutputStreamOperator<TrafficPageViewBean> windowAndAgg(SingleOutputStreamOperator<TrafficPageViewBean> beanStream) {
        // NoKeyBy 聚合:  开窗: WindowAll 每维度, 所有的数据在一起聚和, 窗口处理函数的并行度只能是 1
        // keyBy 聚合: 并行度没有限制

        // 窗口处理函数:
        // 增量: sum max min   reduce  aggregate
        // 全量: process

        return beanStream.assignTimestampsAndWatermarks(WatermarkStrategy.<TrafficPageViewBean>forBoundedOutOfOrderness(Duration.ofSeconds(3)).withTimestampAssigner((bean, ts) -> bean.getTs()).withIdleness(Duration.ofMillis(1))).keyBy(bean -> bean.getCh() + "_" + bean.getAr() + "_" + bean.getVc() + "_" + bean.getIsNew()).window(TumblingEventTimeWindows.of(Time.seconds(5))).reduce(new ReduceFunction<TrafficPageViewBean>() {
                    @Override
                    public TrafficPageViewBean reduce(TrafficPageViewBean bean1, TrafficPageViewBean bean2) throws Exception {
                        bean1.setPvCt(bean1.getPvCt() + bean2.getPvCt());
                        bean1.setSvCt(bean1.getSvCt() + bean2.getSvCt());
                        bean1.setUvCt(bean1.getUvCt() + bean2.getUvCt());
                        bean1.setDurSum(bean1.getDurSum() + bean2.getDurSum());

                        return bean1;
                    }
                },
                // 泛型一: 表示输入. 前面的聚和 结果 的类型.
                new ProcessWindowFunction<TrafficPageViewBean, TrafficPageViewBean, String, TimeWindow>() {
                    @Override
                    public void process(String key,  // key 的值
                                        Context ctx,  // 上下文对象
                                        Iterable<TrafficPageViewBean> elements, // 存储的当前这个窗口最终聚合结果: 这个集和有且仅有一个值
                                        Collector<TrafficPageViewBean> out) throws Exception {
                        TrafficPageViewBean bean = elements.iterator().next();
                        // 补充窗口开始和结束
                        bean.setStt(AtguiguUtil.toDatTime(ctx.window().getStart()));
                        bean.setEdt(AtguiguUtil.toDatTime(ctx.window().getEnd()));

                        // 表示这个结果的统计时间
                        bean.setTs(System.currentTimeMillis());
                        out.collect(bean);
                    }
                });

    }

    private SingleOutputStreamOperator<TrafficPageViewBean> parseToPojo(DataStreamSource<String> stream) {
        return stream.map(JSON::parseObject).keyBy(obj -> obj.getJSONObject("common").getString("mid")).map(new RichMapFunction<JSONObject, TrafficPageViewBean>() {

            private ValueState<String> dateState;

            @Override
            public void open(Configuration parameters) throws Exception {
                dateState = getRuntimeContext().getState(new ValueStateDescriptor<String>("dateState", String.class));
            }

            @Override
            public TrafficPageViewBean map(JSONObject obj) throws Exception {

                JSONObject common = obj.getJSONObject("common");
                JSONObject page = obj.getJSONObject("page");

                String vc = common.getString("vc");
                String ar = common.getString("ar");
                String ch = common.getString("ch");
                String isNew = common.getString("is_new");
                Long ts = obj.getLong("ts");


                Long pvCt = 1L;
                Long durSum = page.getLong("during_time");

                Long svCt = 0L;
                String lastPageId = page.getString("last_page_id");
                if (lastPageId == null || lastPageId.length() == 0) {
                    svCt = 1L;
                }
                Long uvCt = 0L;

                // 状态中存储年月日, 如果来的数据的日期和状态不一样, 就是当天第一条 uvCt=1 更新状态,
                // 否则就不是第一条
                String date = dateState.value();
                String today = AtguiguUtil.toDate(ts);
                if (!today.equals(date)) {
                    // 更新状态
                    dateState.update(today);
                    uvCt = 1L;
                }

                return new TrafficPageViewBean("", "", vc, ch, ar, isNew, uvCt, svCt, pvCt, durSum, ts);
            }
        });
    }
}
